<template>
  <div class="me-allct-body" v-title data-title="个人信息 - For Fun">
    <el-container class="me-allct-container">
      <el-main>
        <el-row :gutter="24">
          <el-col
            :xs="24"
            :sm="24"
            :md="8"
            :lg="6"
            :xl="7"
            style="margin-bottom: 10px"
          >
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>个人信息</span>
              </div>
              <div>
                <div style="text-align: center">
                  <div class="el-upload">
                    <img
                      :src="
                        userInfo.avatarName
                          ? 'http://localhost:8000/api' +
                            '/avatar/' +
                            userInfo.avatarName
                          : Avatar
                      "
                      title="点击上传头像"
                      class="avatar"
                      @click="toggleShow"
                    />
                    <myUpload
                      v-model="show"
                      :headers="headers"
                      :url="updateAvatarApi"
                      @crop-upload-success="cropUploadSuccess"
                      @crop-upload-fail="cropUploadFail"
                    />
                  </div>
                </div>
                <ul class="user-info">
                  <li>
                    <div style="height: 100%">
                      <i class="el-icon-edit"></i> 登录账号
                      <div class="user-right">{{ userInfo.account }}</div>
                    </div>
                  </li>
                  <li>
                    <i class="el-icon-mobile-phone"></i> 手机号码
                    <div class="user-right">{{ userInfo.phone }}</div>
                  </li>
                  <li>
                    <i class="el-icon-unlock"></i> 安全设置
                    <div class="user-right">
                      <a
                        @click="$refs.pass.dialog = true"
                        style="cursor:pointer"
                        >修改密码</a
                      >
                    </div>
                  </li>
                </ul>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="17">
            <!--    用户资料    -->
            <el-card class="box-card">
              <el-tabs v-model="activeName">
                <el-tab-pane label="用户资料" name="first">
                  <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    style="margin-top: 10px;"
                    size="small"
                    label-width="80px"
                  >
                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="昵称" prop="nickname">
                          <el-input v-model="form.nickname" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="管理员" prop="admin">
                          <el-input
                            :disabled="true"
                            :value="form.admin == 0 ? '否' : '是'"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-form-item label="操作">
                      <el-button
                        :loading="saveLoading"
                        size="mini"
                        type="primary"
                        @click="doSubmit"
                        >保存配置</el-button
                      >
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane label="登录日志" name="second">
                  <el-table :data="tableData" style="width: 100%" height="300">
                    <el-table-column
                      prop="requestIp"
                      label="请求IP"
                      width="180"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="time"
                      label="登陆时间"
                      sortable
                      width="180"
                      :formatter="dateFormat"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="address"
                      label="登录地址"
                      width="180"
                    >
                    </el-table-column>
                    <el-table-column prop="browser" label="浏览器" width="180">
                    </el-table-column>
                  </el-table>
                  <!-- 分页 -->
                  <div class="page">
                    <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="queryInfo.pageNum"
                      :page-sizes="[5, 10, 20, 30]"
                      :page-size="queryInfo.pageSize"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="total"
                    >
                    </el-pagination>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-card>
          </el-col>
        </el-row>
        <updatePass ref="pass" />
      </el-main>
    </el-container>
  </div>
</template>

<script>
import myUpload from "vue-image-crop-upload";
import Avatar from "@/assets/img/avatar.png";
import updatePass from "./updatePass";
import { updateUser, getUserInfoByToken, getLog } from "@/api/blog";
import store from "@/store";

export default {
  name: "myInfo",
  components: { myUpload, updatePass },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else if (!isvalidPhone(value)) {
        callback(new Error("请输入正确的11位手机号码"));
      } else {
        callback();
      }
    };

    const validCard = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入身份证号码"));
      } else if (!isCardNo(value)) {
        callback(new Error("请输入正确的身份证号码"));
      } else {
        callback();
      }
    };

    const validIsEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入邮箱"));
      } else if (!validEmail(value)) {
        callback(new Error("请输入正确的邮箱地址"));
      } else {
        callback();
      }
    };

    return {
      reverse: true,
      updateAvatarApi: "http://localhost:8000/api/upload/avatar",
      show: false,
      activeName: "first",
      form: {},
      total: 0,
      Avatar: Avatar,
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
      },

      tableData: [],
      deptName: "",
      roleName: "",
      saveLoading: false,
      userInfo: {},
      rules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        telephone: [{ required: true, trigger: "blur", validator: validPhone }],
      },
      headers: {
        "Oauth-Token": this.$store.state.token,
      },
    };
  },
  methods: {
    //时间格式化
    dateFormat: function(row, column) {
      var date = row[column.property];
      var moment = require("moment");
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    formatTime(value) {
      var moment = require("moment");
      if (value == undefined) {
        return "";
      }
      return moment(value).format("YYYY-MM-DD HH:mm:ss");
    },
    //获取用户相关信息
    GetInfo() {
      const that = this;
      getUserInfoByToken().then((res) => {
        that.userInfo = res.result;
        console.log("userinfo", that.userInfo);
        that.form = res.result;
      });
    },
    //上传成功回调
    cropUploadSuccess(jsonData, field) {
      console.log("-------- upload success --------");
      console.log(jsonData);
      console.log("field: " + field);
      this.GetInfo();
      store.dispatch("getUserInfo").then(() => {});
    },
    //上传失败回调
    cropUploadFail(status, field) {
      console.log("-------- upload fail --------");
      console.log("上传失败状态" + status);
      console.log("field: " + field);
    },
    toggleShow() {
      this.show = !this.show;
    },
    // 截图成功回调函数
    cropSuccess(imgDataUrl, field) {
      console.log("-------- crop success --------", imgDataUrl, field);
    },
    doSubmit() {
      const that = this;
      if (this.$refs["form"]) {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.saveLoading = true;
            updateUser(this.form)
              .then((response) => {
                if (response.code == 200) {
                  that.$notify({
                    title: response.message,
                    type: "success",
                    duration: 1500,
                  });
                  this.saveLoading = false;
                  that.getUserInfoByToken();
                }
              })
              .catch(() => {
                this.saveLoading = false;
              });
          }
        });
      }
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getLog();
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getLog();
    },
    async getLog() {
      const that = this;
      await getLog(this.queryInfo).then((resp) => {
        if (resp.code == 200) {
          that.tableData = resp.result.list;
          that.total = resp.result.total;
        } else {
          that.$message.warning(resp.message);
        }
      });
    },
  },
  computed: {
    user() {
      return this.$store.state.user;
    },
  },
  created() {
    this.GetInfo();
    this.getLog();
  },
};
</script>

<style lang="less" scoped>
.me-allct-body {
  width: 55%;
}
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}
.user-info {
  padding-left: 0;
  list-style: none;
  li {
    border-bottom: 1px solid #f0f3f4;
    padding: 11px 0;
    font-size: 13px;
  }
  .user-right {
    float: right;
    a {
      color: #317ef3;
    }
  }
}

.page {
  display: flex;
  justify-content: flex-end;
}
</style>
